package cc.cc4414.spring.mybatis.config;

import cc.cc4414.spring.mybatis.entity.BaseEntity;
import cc.cc4414.spring.resource.core.CommonUser;
import cc.cc4414.spring.resource.util.UserUtils;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自动填充处理器
 *
 * @author cc 2019年11月3日
 */
@Component
@ConditionalOnMissingBean(MetaObjectHandler.class)
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        CommonUser user = UserUtils.getUser();
        // CommonUser中的部门id和部门名称在用户登录时会使用用户所在部门替换（数据库中为创建该用户者所在部门）
        this.strictInsertFill(metaObject, BaseEntity.FIELD_DEPT_ID, String.class, user.getDeptId());
        this.strictInsertFill(metaObject, BaseEntity.FIELD_DEPT_NAME, String.class, user.getDeptName());
        this.strictInsertFill(metaObject, BaseEntity.FIELD_DELETED, Integer.class, 0);
        this.strictInsertFill(metaObject, BaseEntity.FIELD_DISABLED, Integer.class, 0);
        this.strictInsertFill(metaObject, BaseEntity.FIELD_GMT_CREATE, LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, BaseEntity.FIELD_CREATOR_ID, String.class, user.getId());
        this.strictInsertFill(metaObject, BaseEntity.FIELD_CREATOR_NAME, String.class, user.getName());
        this.strictInsertFill(metaObject, BaseEntity.FIELD_GMT_MODIFIED, LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, BaseEntity.FIELD_MODIFIER_ID, String.class, user.getId());
        this.strictInsertFill(metaObject, BaseEntity.FIELD_MODIFIER_NAME, String.class, user.getName());
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        CommonUser user = UserUtils.getUser();
        this.strictUpdateFill(metaObject, BaseEntity.FIELD_GMT_MODIFIED, LocalDateTime.class, LocalDateTime.now());
        this.strictUpdateFill(metaObject, BaseEntity.FIELD_MODIFIER_ID, String.class, user.getId());
        this.strictUpdateFill(metaObject, BaseEntity.FIELD_MODIFIER_NAME, String.class, user.getName());
    }
}
